import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

const store=new Vuex.Store({
    state: {
        data:"我是vuex中的数据",
        car:[],
    },
    getters:{
        howMuch(store){
            var sum=0;
            for(let n of store.car){
                sum+=parseFloat(n.price)*n.count;
            }
            return sum.toFixed(2);
        }
    },
    mutations:{
        addItem(store,obj){
            const old=store.car.find(item=>item.id===obj.id);
            // console.log(old)
            if(old){
                if(obj.addtion&&obj.addtion>0){
                    old.count+=obj.addtion;
                    obj.addtion=0;
                }
                else old.count+=1;
            }else {
                if(obj.addtion&&obj.addtion>0){
                    obj.count=obj.addtion;
                }
                else obj.count=1;
                store.car.push(obj);
            }
        },
        remove(store,payload){
            var i=0;
            store.car.filter(function (a){
                if(a.id===payload.id) {
                    console.log("移除商品:["+payload.id+payload.title+"]");
                    store.car.splice(i,1);
                }
                i++;
            })
        },

    },
    actions:{},
    modules:{}
})

export default store